#!/usr/bin/python
# -*- coding: utf-8 -*-
import time, xlwt, os
from db import get_conn

prefix = os.path.split(os.path.realpath(__file__))[0]


def log(msg):
    conn = get_conn()
    cursor = conn.cursor()

    msg_id = msg.msgId
    msg_timestamp = msg.createTime
    chatroom_id = msg.user.userName
    chatroom_name = msg.user.nickName
    user_id = msg.actualUserName
    user_nickname = msg.actualNickName
    context_type = msg.type
    context_text = msg.text
    # print msg_id, msg_timestamp, chatroom_id, chatroom_name, user_id, user_nickname, context_type, context_text

    sql = 'INSERT INTO chatroom_record(msg_id, msg_timestamp, chatroom_id, chatroom_name, user_id, user_nickname, context_type, context_text)' \
          ' VALUES (%s, %s, %s, %s, %s, %s, %s, %s)'
    param = (msg_id, msg_timestamp, chatroom_id, chatroom_name, user_id, user_nickname, context_type, context_text)

    try:
        cursor.execute(sql, param)
    except Exception, e:
        print e

    conn.commit()
    cursor.close()
    conn.close()

    return


def download():
    return dump('wechat_data_' + current_time() + '.xls')


def dump(file_name):
    url = prefix + '/data/' + file_name

    conn = get_conn()
    cursor = conn.cursor()

    sql = 'SELECT id, gmt_create, msg_id, msg_timestamp, chatroom_id, chatroom_name, user_id, user_nickname, context_type, context_text ' \
          'FROM chatroom_record ' \
          'ORDER BY chatroom_id, id;'
    cursor.execute(sql)

    # cursor.scroll(0, mode='absolute')

    results = cursor.fetchall()

    fields = cursor.description
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet('data', cell_overwrite_ok=True)

    for field in range(0, len(fields)):
        sheet.write(0, field, fields[field][0])

    for row in range(1, len(results) + 1):
        for col in range(0, len(fields)):
            sheet.write(row, col, u'%s' % results[row - 1][col])

    workbook.save(url)
    return url


def get_nickname(user_id, member_list):
    for member in member_list:
        if member['UserName'] == user_id:
            return member['NickName']


def current_time():
    return str(time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()))


download()
